import React, { Component } from "react";
import { withRouter } from "react-router-dom";
import { Tree, message, Button, Modal } from "antd";
import { AllAuthority, UpdateAuthority, UserInfo } from "../../api";
import store from '../../store'

class Back extends Component {
  constructor(props) {
    super(props);
    this.state = {
      treeData: [],
      checkedKeys: [],
      username: "",
    };
  }
  componentDidMount() {
    AllAuthority().then((res) => {
      var arr = [
        {
          key: "all",
          title: "权限控制",
          children: [],
        },
      ];
      res.forEach((item) => {
        let obj = {};
        obj.key = item._id;
        obj.title = item.title;
        arr[0].children.push(obj);
      });
      this.setState({
        treeData: arr,
      });
    });
    if (this.props.location.query) {
      var _id = this.props.location.query.id || undefined;
      if (_id) {
        UserInfo({ uid: _id }).then((res) => {
          this.setState({
            checkedKeys: res[0].resource,
            username: res[0].username,
          });
        });
      }
    }
  }
  onSubmit = () => {
    UpdateAuthority({
      resource: this.state.checkedKeys,
      uid: this.props.location.query.id,
    }).then((res) => {
      if (res) {
        Modal.info({
          title: "修改权限成功",
          centered: true,
        });
      }
    });
  };
  onCheck = (checkedKeys) => {
    let index = checkedKeys.indexOf("all");
    if (index > -1) {
      checkedKeys.splice(index, 1);
    }
    this.setState({
      checkedKeys,
    });
  };
  render() {
    return (
      <div>
        {
          this.props.location.query ? 
          (<div >
            <h1 style={{ textAlign: "left", fontSize: "25px" }}>
              {this.state.username}的权限
            </h1>
            <Tree
              checkable
              checkedKeys={this.state.checkedKeys}
              onCheck={this.onCheck}
              treeData={this.state.treeData}
            />
            <Button
              type="primary"
              danger
              style={{ marginLeft: "50px", marginTop: "25px" }}
              onClick={this.onSubmit}
            >
              提交
            </Button>
          </div>) : (<div>请去前端页面查看用户</div>)
        }
        
      </div>
    );
  }
}

export default withRouter(Back);
